//
//  DownloadViewController.m
//  51-Tour
//
//  Created by xiang ying on 14-3-20.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "DownloadViewController.h"
#import "ScenicCell.h"
#import "DownloadCell.h"
#import "ServiceManage.h"
#import "SVProgressHUD.h"
#import "DownloadManagement.h"
#import "db_Downloading.h"

@interface DownloadViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>{
    
    UISegmentedControl *tabChoose;
    
    UITableView *_downloadList,*_scenicsList;
    
    CityDTO    *_city;
    
    NSMutableArray *_scenicsArray,*_downloadArray;
    
    BOOL        needUpdate;
    language_type   languageType;
    
}

@end

@implementation DownloadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadList:) name:UPDATELIST object:nil];
        
        needUpdate = YES;
        languageType = unknow;
    }
    return self;
}


- (void)setCity:(CityDTO*)city{
    if (_city!= city||[[DataCenter instance] getLanguageType]!=languageType) {
        needUpdate = YES;
    }else{
        needUpdate = NO;
    }
    _city = city;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNavigationItme:_city.cityName];
    
    _scenicsArray = [NSMutableArray array];
    
    _downloadArray = [db_Downloading searchAllDownloads];
    
    _scenicsList = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, 320, self.contentView.frame.size.height-44)];
    _scenicsList.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_scenicsList setBackgroundColor:[UIColor clearColor]];
    _scenicsList.dataSource = self;
    _scenicsList.delegate = self;
    [self.contentView addSubview:_scenicsList];
    
    _downloadList = [[UITableView alloc] initWithFrame:CGRectMake(320, 40, 320, self.contentView.frame.size.height-44)];
    _downloadList.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_downloadList setBackgroundColor:[UIColor clearColor]];
    _downloadList.dataSource = self;
    _downloadList.delegate = self;
    [self.contentView addSubview:_downloadList];
    
    tabChoose = [[UISegmentedControl alloc] initWithItems:@[[[DataCenter instance] getStringForKey:@"scenidList"],[[DataCenter instance] getStringForKey:@"DownloadCenter"]]];
    tabChoose.frame = CGRectMake(20, self.contentView.frame.origin.y+5, 280, 30);
    [tabChoose setTintColor:THEMECOLOR];
    [tabChoose setSelectedSegmentIndex:0];
    [tabChoose addTarget:self action:@selector(tabChoose:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:tabChoose];
    
    [self.contentView setContentSize:CGSizeMake(640, self.contentView.frame.size.height)];
    self.contentView.showsHorizontalScrollIndicator = NO;
    self.contentView.delegate = self;
    self.contentView.pagingEnabled = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //加载城市景点列表
    [self initNavigationItme:_city.cityName];
    languageType = [[DataCenter instance] getLanguageType];

    [tabChoose setTitle:[[DataCenter instance] getStringForKey:@"scenidList"] forSegmentAtIndex:0];
    [tabChoose setTitle:[[DataCenter instance] getStringForKey:@"DownloadCenter"] forSegmentAtIndex:1];

    [SVProgressHUD showWithStatus:[[DataCenter instance] getStringForKey:@"loading"]];
    NSDictionary *info = @{@"CityCode": _city.cityCode,@"LanKey":@"zh-cn"};
    if ([[DataCenter instance] getLanguageType] == en_us) {
        info = @{@"CityCode": _city.cityCode,@"LanKey":@"en-us"};
    }
    [_scenicsArray removeAllObjects];
    [_scenicsList reloadData];
    [ServiceManage getCityscenicesRequestInfo:info completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            [SVProgressHUD dismiss];
            [_scenicsArray addObjectsFromArray:respond.data];
            [_scenicsList reloadData];
            [_downloadList reloadData];
        }else if(respond.flag == respond_nodata){
            [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"noscenic"]];
        }else{
            [SVProgressHUD showErrorWithStatus:TIP_ERROR];
        }
    }];

    
//    if (needUpdate) {
//        //加载城市景点列表
//        [self initNavigationItme:_city.cityName];
//        languageType = [[DataCenter instance] getLanguageType];
//        [SVProgressHUD showWithStatus:@"获取中..."];
//        NSDictionary *info = @{@"CityCode": _city.cityCode,@"LanKey":@"zh-cn"};
//        if ([[DataCenter instance] getLanguageType] == en_us) {
//            info = @{@"CityCode": _city.cityCode,@"LanKey":@"en-us"};
//        }
//        [_scenicsArray removeAllObjects];
//        [_scenicsList reloadData];
//        [ServiceManage getCityscenicesRequestInfo:info completion:^(RespondDTO *respond) {
//            if (respond.flag == respond_success) {
//                [SVProgressHUD dismiss];
//                [_scenicsArray addObjectsFromArray:respond.data];
//                [_scenicsList reloadData];
//            }else {
//                [SVProgressHUD showErrorWithStatus:respond.msg];
//            }
//        }];
//    }
    [tabChoose setSelectedSegmentIndex:0];
    [self tabChoose:tabChoose];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)tabChoose:(id)sender{
    if (tabChoose.selectedSegmentIndex == 0) {
        [self initNavigationItme:_city.cityName];
    }else{
        [self initNavigationItme:[[DataCenter instance] getStringForKey:@"DownloadCenter"]];
    }
    
    [self.contentView scrollRectToVisible:CGRectMake(320*tabChoose.selectedSegmentIndex, 0, 320, self.contentView.frame.size.height) animated:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.contentView) {
        if (scrollView.contentOffset.x == 0) {
            [tabChoose setSelectedSegmentIndex:0];
            [self initNavigationItme:_city.cityName];
        }else{
            [tabChoose setSelectedSegmentIndex:1];
            [self initNavigationItme:[[DataCenter instance] getStringForKey:@"DownloadCenter"]];
        }
    }
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _scenicsList) {
        return _scenicsArray.count;
    }
    return _downloadArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _scenicsList) {
        ScenicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[ScenicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        [cell updateWithData:_scenicsArray[indexPath.row]];
        return cell;
    }
    DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    if (!cell) {
        cell = [[DownloadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
    }
    [cell updateWithData:_downloadArray[indexPath.row]];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _scenicsList) {
        return ScenicCellHeight;
    }
    return DownloadCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -ScenicCellDelegate
-(void)reloadList:(NSNotification*)scene{
    [_downloadList reloadData];
}

@end
